import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Modal, message, Select } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';
import AuthComponent from '@/components/Authorized/AuthComponent';
import { templates, delTerminal, save, update, deleteTemplate, getSelectDict } from './service'
import SmsTemplateConfigAddOrEditForm from './components/SmsTemplateConfigAddOrEditForm'

const SmsTemplateConfiguration = () => {

  const actionRef = useRef();
  const ref = useRef()

  // 新增、编辑弹窗显隐
  const [smsTemplateConfigAddOrEditFormVisible, handleSmsTemplateConfigAddOrEditFormVisible] = useState(false)
  // 弹窗名称
  const [modalTitle, handleModalTitle] = useState('')
  // 配置id
  const [templateId, handleTemplateId] = useState('')
  // 多选
  const [selectedRowKeys, handleSelectedRowKeys] = useState([])

  // 获取短信模板类型
  const { data: templateTypeD = [] } = useRequest(params => getSelectDict({ dataTypeCode: 'sms_template_type' }))
  // 删除接口
  const { run: deleteTemplateR } = useRequest(params => deleteTemplate(params), {
    manual: true,
    onSuccess: (data) => {
      message.success('删除成功')
      actionRef.current.reload()
    }
  })

  // 多选改变时方法
  const onSelectChange = selectedRowKeys => {
    handleSelectedRowKeys(selectedRowKeys)
  };

  // 多选
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange
  };

  // 清空选择性
  const clearSelection = () => {
    handleSelectedRowKeys([])
  };

  // 新增
  const add = () => {
    handleModalTitle('新增短信模板')
    handleTemplateId('')
    handleSmsTemplateConfigAddOrEditFormVisible(true)
  }

  // 修改
  const edit = (selectedRows) => {
    if (selectedRows.length === 0) {
      message.warning('请至少选择一项')
    } else if (selectedRows.length > 1) {
      message.warning('只能选择一项')
    } else {
      handleModalTitle('修改短信模板')
      handleTemplateId(selectedRows[0].id)
      handleSmsTemplateConfigAddOrEditFormVisible(true)
    }
  }

  // 新增/编辑回调
  const handleSmsTemplateConfig = async fields => {
    delete fields.templateSign
    try {
      if (templateId === '') {
        await save(fields)
      } else {
        await update({
          id: templateId,
          ...fields
        })
      }
      return true
    } catch (error) {
      if (templateId === '') {
        message.error('新增失败请重试！');
      } else {
        message.error('修改失败请重试！');
      }
      return false
    }
  }

  // 删除
  const del = (selectedRows) => {
    if (selectedRows.length === 0) {
      message.warning('请至少选择一项')
    } else {
      Modal.confirm({
        title: '删除',
        content: '确认删除该数据？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          let ids = []
          selectedRows.map(item => {
            ids.push(item.id)
          })
          deleteTemplateR({ id: ids })
        }
      });
    }
  }

  const columns = [
    {
      title: '短信类型',
      dataIndex: 'templateCode',
      width: 240,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            allowClear={true}
            placeholder='请选择'
            onChange={onChange}
            value={value ? value : ''}
          >
            {
              templateTypeD.map(item => (
                <Select.Option key={item.dataCode} title={item.dataRemark}>{item.dataRemark}</Select.Option>
              ))
            }
          </Select>
        );
      },
      render: (text, _) => (
        <div>
          <span>{text === 'luggage_express' ? '行查系统快递单短信通知模板' : ''}</span>
          <span>{text === 'VIP_SMS' ? '贵宾厅旅客进厅短信（自动）' : ''}</span>
        </div>

      )
    },
    {
      title: '短信名称',
      dataIndex: 'templateName',
      width: 180
    },
    {
      title: '短信内容',
      dataIndex: 'templateContent',
      ellipsis: true
    }
  ];
  return (
    <>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        rowKey="id"
        className={styles.smsTemplateConfiguration}
        headerTitle={
          <div>
            <span style={{ fontWeight: "700", color: "rgba(0,0,0,0.85)", fontSize: '16px' }}>短信模板数据列表</span>
          </div>
        }
        options={{ fullScreen: true, reload: false, setting: true, density: false }}
        rowSelection={rowSelection}
        search={{
          span: 6
        }}
        toolBarRender={(action, { selectedRows }) => [
          <AuthComponent authCode='basicInformation.smsTemplateConfiguration.basic'>
            <Button type="primary" onClick={() => add()} size="small">
              新增
            </Button>
          </AuthComponent>,
          <AuthComponent authCode='basicInformation.smsTemplateConfiguration.edit'>
            <Button type="primary" onClick={() => edit(selectedRows)} size="small">
              修改
            </Button>
          </AuthComponent>,
          <AuthComponent authCode='basicInformation.smsTemplateConfiguration.del'>
            <Button type="primary" onClick={() => del(selectedRows)} size="small">
              删除
            </Button>
          </AuthComponent>
        ]}
        tableAlertRender={false}
        request={params => {
          clearSelection()
          return templates(params)
        }}
        columns={columns}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
          defaultPageSize: 20,
          pageSizeOptions: ['20', '30', '40']
        }}
        scroll={{ x: 900, y: 190 }}
      />
      {
        smsTemplateConfigAddOrEditFormVisible && <SmsTemplateConfigAddOrEditForm
          onSubmit={async value => {
            const success = await handleSmsTemplateConfig(value)
            if (success) {
              if (templateId === '') {
                message.success('新增成功')
              } else {
                message.success('编辑成功')
              }
              handleSmsTemplateConfigAddOrEditFormVisible(false)
              actionRef.current.reload()
            }
          }}
          onCancel={() => handleSmsTemplateConfigAddOrEditFormVisible(false)}
          smsTemplateConfigAddOrEditFormVisible={smsTemplateConfigAddOrEditFormVisible}
          modalTitle={modalTitle}
          templateId={templateId}
        ></SmsTemplateConfigAddOrEditForm>
      }
    </>
  );
};

export default Form.create()(SmsTemplateConfiguration);
